#!/bin/bash
#
################################################################################
# Count lines of code.
#
# Usage:  loc.sh dir [dir2 [...]]
#
# where dir_n are directories to look for source files in.
#
# Counting lines of code is a subjective matter.  This utility considers a line
# to be a line of code (and thus count it) iff the line follows the following
# rules:
#
#  1. The line is not a blank line or a line comment:
#
#     // this is a comment
#
#     will not be counted.
#
#  2. The line does not consist solely of grouping characters.  Grouping
#     characters are the [, {, (, < characters and their
#     counterparts:
#
#     }
#
#     will not be counted.
#
#  3. Semicolons are also ignored:
#
#     };
#
#     will not be counted.
#
# At the moment the script does not handle multi-line comments, although it
# should probably ignore these as well.
################################################################################

if [ $# -eq 0 ]; then
    echo "Usage:  $0 dir [dir2 [...]]"
    exit
fi

SUM_LINES=0;
for DIR in "$@"; do
    DIR=$(echo "$DIR" |sed 's/\/*$//g') # remove trailing slash
    for FILE in $DIR/*.{h,cpp}; do
        # count lines in current file, according to regex as at top of file
        LINES=$(perl -pne 's/^\s*([<>\[\](){}]|\/\/.*)?\s*;*\s*$//' $FILE |wc -l);
        # maintain a total
        SUM_LINES=$(($SUM_LINES+$LINES));
        echo -e "$LINES\t$FILE";
    done;
done;
echo "$SUM_LINES total";
